<template>
  <NavigateBar></NavigateBar>
  <div class="home">
    <div class="chatHome">
      <div class="chatLeft">
        <!-- 新建会话按钮，点击后触发 createChat 方法 -->
        <NewButton style="margin-left: 10px; margin-bottom: 20px" @click="createChat"></NewButton>
        <div class="online-person">
          <div class="person-cards-wrapper">
            <!-- 循环渲染会话列表 -->
            <div
                class="conversationList"
                v-for="conversationInfo in conversationList"
                :key="conversationInfo.conversationId"
                @click="clickPerson(conversationInfo)"
            >
              <!-- 会话卡片组件 -->

              <ConversationCard
                  :conversationInfo="conversationInfo"
                  :pcCurrent="pcCurrent"
                  @deleteConversation="deleteConversation"
                  @renameConversation="renameConversation"
              ></ConversationCard>
            </div>
          </div>
        </div>
      </div>
      <div class="chatRight">
        <GPTWindow
            :conversationInfo="chatWindowInfo"
            @convCardSort="convCardSort"
            @updateConversationList="updateConversationList"
        ></GPTWindow>
      </div>


    </div>
  </div>
</template>



<script setup>
// 引入必要的组件和方法
import ConversationCard from "@/components/gpt/ConversationCard.vue";
import GPTWindow from "./GPTWindow.vue";
import { getChatgptLog, deleteChatgptConversation, renameChatgptConversation } from "@/api/getSession.ts";
import { ref, onMounted, reactive } from "vue";
import { useUserStore } from "@/stores/user";
import NavigateBar from "@/components/base/NavigateBar.vue";
import NewButton from "@/components/gpt/NewButton.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";

// 核心变量
const pcCurrent = ref("");  // 当前选中的会话ID
const conversationList = ref([]);  // 会话列表数据
const chatWindowInfo = ref({});  // 当前聊天窗口会话信息
const router = useRouter();  // 路由实例
const userStore = reactive(useUserStore());  // 用户状态

// 初始化时加载会话记录
onMounted(() => {
  getChatgptLog()
      .then((res) => {
        conversationList.value = res;  // 将会话记录赋值到会话列表
      })
      .catch(() => {
        handleLogout();  // 加载失败时执行登出逻辑
      });
});

// 更新会话列表并设置当前会话
function updateConversationList(newConversation) {
  // 在列表顶部插入新会话
  conversationList.value.unshift({
    conversationId: newConversation.conversationId,
    conversationName: newConversation.conversationName,
  });
  pcCurrent.value = newConversation.conversationId;  // 设置当前选中的会话ID
}

// 处理会话点击事件
function clickPerson(info) {
  chatWindowInfo.value = info;  // 设置当前聊天窗口的会话信息
  pcCurrent.value = info.conversationId;  // 设置当前选中的会话ID
}

// 将指定会话移动到列表顶部
function convCardSort(id) {
  const index = conversationList.value.findIndex(item => item.conversationId === id);
  if (index > 0) {
    const [conversation] = conversationList.value.splice(index, 1);  // 移除当前会话
    conversationList.value.unshift(conversation);  // 将会话移至列表顶部
  }
}

// 删除指定会话
function deleteConversation(id) {
  deleteChatgptConversation(id).then(() => {
    // 从会话列表中移除已删除的会话
    conversationList.value = conversationList.value.filter(item => item.conversationId !== id);
  });
}

// 创建新会话
function createChat() {
  resetChatWindow();  // 重置聊天窗口
  clickPerson(chatWindowInfo.value);  // 选择当前会话
}

// 重置聊天窗口信息
function resetChatWindow() {
  chatWindowInfo.value = { conversationId: null};  // 清空当前会话信息
  pcCurrent.value = null;  // 清空当前选中会话ID
}

// 处理会话重命名
function renameConversation(id) {
  ElMessageBox.prompt('请输入新名称', '重命名', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
  })
      .then(({ value }) => {
        if (value) {
          renameChatgptConversation(id, value).then(() => {
            const conversation = conversationList.value.find(item => item.conversationId === id);
            if (conversation) {
              conversation.conversationName = value;  // 更新会话名称
            }
          });
        }
      })
      .catch(() => {});
}

// 处理登出逻辑
function handleLogout() {
  localStorage.clear();  // 清空本地存储
  userStore.$patch({ token: '' });  // 清空用户token
  userStore.$patch({ user: {} });  // 清空用户信息
  ElMessage({
    showClose: true,
    message: '对不起，此功能需要登录后使用！',
    type: 'warning',
  });
  router.push({ name: 'login' });  // 跳转至登录页面
}
</script>

<style lang="scss" scoped>
.home {
  width: 100%;
  height: 100%;
  background-color: #343541; /* 背景颜色调整为深色 */
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  z-index: -1;
}
.chatHome {
  margin-top: 86px;
  margin-left: 20px;
  display: flex;
  .chatLeft {
    .title {
      color: #d1d5db; /* 标题颜色调整为浅色 */
      padding-left: 10px;
    }
    .online-person {
      .online-text {
        padding-left: 10px;
        color: #a3a3a3; /* 在线人数文字颜色调整为浅灰色 */
      }
      .person-cards-wrapper {
        padding-left: 10px;
        height: 75vh;
        overflow: hidden;
        overflow-y: scroll;
        box-sizing: border-box;
        &::-webkit-scrollbar {
          width: 0; /* Safari,Chrome 隐藏滚动条 */
          height: 0; /* Safari,Chrome 隐藏滚动条 */
          display: none; /* 移动端、pad 上Safari，Chrome，隐藏滚动条 */
        }
      }
    }
  }

  .chatRight {
    width: 100%;
    padding-right: 30px;
  }

  .default-area {
    width: 90%;
    background-color: #4a4a4a; /* 默认区域背景颜色调整为中深灰色 */
    border-radius: 20px;
    display: flex;
    margin: auto;
    content: "";
    opacity: 0.5;
  }

  .default-image {
    display: flex;
    margin: auto;
    width: 85vh;
    height: 85vh;
  }
}

@media screen and (max-width: 768px) {
  .chatHome {
    .chatLeft {
      display: none;
    }
  }
}
</style>
